package main

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"

	_ "github.com/lib/pq"
)

type Book struct {
	Id      int
	Balance float32 `db:"balance"`
}

var db *sql.DB

func init() {
	var (
		crt = "certs/ca.crt"
		key = "certs/client.root.key"
		pem = "certs/client.root.crt"
	)

	var err error
	dsn := fmt.Sprintf("postgres://root@192.168.152.134:26257/bank?sslmode=verify-ca&sslrootcert=%s&sslkey=%s&sslcert=%s", crt, key, pem)
	db, err = sql.Open("postgres", dsn)
	if err != nil {
		log.Fatal(err)
	}

	if err = db.Ping(); err != nil {
		log.Fatal(err)
	}
	log.Println("connect to database success")
}

func main() {
	http.HandleFunc("/bank", booksIndex)
	http.ListenAndServe(":9090", nil)
}

func booksIndex(w http.ResponseWriter, r *http.Request) {

	if r.Method != "GET" {
		http.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)
		return
	}

	log.Println("get books index")
	rows, err := db.Query("SELECT * FROM accounts")

	if err != nil {
		http.Error(w, http.StatusText(500), 500)
		return
	}
	defer rows.Close()

	bks := make([]*Book, 0)

	for rows.Next() {
		bk := new(Book)
		err := rows.Scan(&bk.Id, &bk.Balance)
		if err != nil {
			http.Error(w, http.StatusText(500), 500)
			return
		}
		bks = append(bks, bk)
	}

	if err = rows.Err(); err != nil {
		http.Error(w, http.StatusText(500), 500)
		return
	}

	fmt.Println("books index:", len(bks))
	for _, bk := range bks {
		fmt.Printf("%d %v \n", bk.Id, bk.Balance)
	}
}
